package com.gupao.javavip.dubbo.client;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.gupao.javavip.dubbo.api.IUserService;
import com.gupao.javavip.dubbo.api.dto.AddUserRequest;
import lombok.extern.apachecommons.CommonsLog;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
@CommonsLog
public class UserService implements ApplicationListener<ContextRefreshedEvent> {
    @Reference(lazy = true)
    private IUserService service;

    @NacosValue(value = "${biz.test-time:1}", autoRefreshed = true)
    private String testTime;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        batchExecuteRPCInvoke();
    }

    public void batchExecuteRPCInvoke() {
        log.info("==================");
        log.info("开始测试，测试次数：" + testTime);
        log.info("==================");

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < Integer.valueOf(testTime); i++) {
            addUser();
        }
        long endTime = System.currentTimeMillis();

        log.info("==================");
        log.info("耗时：" + (endTime - startTime));
        log.info("==================");
    }

    public void addUser() {
        if (log.isDebugEnabled()) {
            log.debug("发起RPC调用");
        }

        try {
            AddUserRequest request = new AddUserRequest();
            request.setAge("12");
            request.setName("test");
            service.addUser(request);
        } catch (Throwable e) {
            log.error("RPC失败：" + e.getMessage());
        }
    }

    public void sayHello() {
        service.sayHello();
    }
}
